package com.sixth.service.impl;

import com.alibaba.nacos.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sixth.core.entity.*;
import com.sixth.core.vo.R;
import com.sixth.mapper.*;
import com.sixth.service.CareOrderItemService;
import com.sixth.vo.CareOrderItemVo;
import com.sixth.vo.CheckResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CareOrderItemServiceImpl extends ServiceImpl<CareOrderItemMapper, CareOrderItem> implements CareOrderItemService {


    @Autowired
    private CareOrderItemMapper careOrderItemMapper;

    @Autowired
    private OrderChargeItemMapper orderChargeItemMapper;

    @Autowired
    private CheckResultMapper checkResultMapper;

    @Autowired
    private CareHistoryMapper careHistoryMapper;

    @Autowired
    private CareOrderMapper careOrderMapper;


    @Override
    public R<IPage<CareOrderItem>> selectByPage(CareOrderItemVo careOrderItemVo) {
        // 创建一个分页对象
        IPage<CareOrderItem> page = new Page<>(careOrderItemVo.getPageNum(), careOrderItemVo.getPageSize());

        String regId = careOrderItemVo.getRegId();

        if (StringUtils.hasText(regId)) {
            // 查询 CareHistory 表
            QueryWrapper<CareHistory> careHistoryQueryWrapper = new QueryWrapper<>();
            careHistoryQueryWrapper.eq("reg_id", regId.trim());

            List<CareHistory> careHistories = careHistoryMapper.selectList(careHistoryQueryWrapper);
            List<String> chId = careHistories.stream().map(CareHistory::getChId).collect(Collectors.toList());
            System.out.println("chId~~~~~~~~~~" + chId);

            if (!chId.isEmpty()) {
                // 查询 CareOrder 表
                QueryWrapper<CareOrder> careOrderQueryWrapper = new QueryWrapper<>();
                careOrderQueryWrapper.in("ch_id", chId);
                careOrderQueryWrapper.eq("co_type", "1");

                List<CareOrder> careOrderList = careOrderMapper.selectList(careOrderQueryWrapper);
                List<String> coId = careOrderList.stream().map(CareOrder::getCoId).collect(Collectors.toList());
                System.out.println("coId~~~~~~~~~~" + coId);

                // 查询 CareOrderItem 表
                QueryWrapper<CareOrderItem> itemWrapper = new QueryWrapper<>();
                if (!coId.isEmpty()) {
                    itemWrapper.in("co_id", coId);
                }
                if (careOrderItemVo.getCheckItemIds() != null && !careOrderItemVo.getCheckItemIds().isEmpty()) {
                    itemWrapper.in("item_ref_id", careOrderItemVo.getCheckItemIds());
                }

                itemWrapper.orderByDesc("create_time");
                itemWrapper.eq("item_type", "1");
                itemWrapper.eq("status", "1");

                IPage<CareOrderItem> careOrderItemPage = careOrderItemMapper.selectPage(page, itemWrapper);
                return R.ok(careOrderItemPage);
            } else {
                // 如果没有找到对应的 CareHistory 记录，则直接返回空的结果集
                return R.ok(page);
            }
        } else {
            // 如果 regId 为空，则直接查询 CareOrderItem 表，忽略其他条件
            QueryWrapper<CareOrderItem> itemWrapper = new QueryWrapper<>();
            itemWrapper.orderByDesc("create_time");
            itemWrapper.eq("item_type", "1");
            itemWrapper.eq("status", "1");

            IPage<CareOrderItem> careOrderItemPage = careOrderItemMapper.selectPage(page, itemWrapper);
            return R.ok(careOrderItemPage);
        }
    }


    @Override
    public R<CareOrderItem> selectById(String itemId) {
        CareOrderItem careOrderItem = careOrderItemMapper.selectByIdItem(itemId);
        return R.ok(careOrderItem);
    }

    @Override
    @Transactional
    public R<CareOrderItem> startCheck(CheckResultVo checkResultVo) {
        try {
            // 构建更新条件
            UpdateWrapper<OrderChargeItem> orderChargeUpdateWrapper = new UpdateWrapper<>();
            orderChargeUpdateWrapper.eq("item_id", checkResultVo.getItemId()).set("status", "3");

            UpdateWrapper<CareOrderItem> careOrderUpdateWrapper = new UpdateWrapper<>();
            careOrderUpdateWrapper.eq("item_id", checkResultVo.getItemId()).set("status", "3");

            // 执行更新操作
            int orderChargeUpdateResult = orderChargeItemMapper.update(null, orderChargeUpdateWrapper);
            int careOrderUpdateResult = careOrderItemMapper.update(null, careOrderUpdateWrapper);

            if (orderChargeUpdateResult > 0 && careOrderUpdateResult > 0) {
                // 写入检查表
                CheckResult checkResult = getCheckResult(checkResultVo);
                checkResultMapper.insert(checkResult);
                return R.ok();
            } else {
                return R.error("500");
            }
        } catch (Exception e) {
            return R.error("500");
        }
    }

    private static CheckResult getCheckResult(CheckResultVo checkResultVo) {
        CheckResult checkResult = new CheckResult();
        checkResult.setCocId(checkResultVo.getItemId());
        checkResult.setCheckItemId(checkResultVo.getItemRefId());
        checkResult.setCheckItemName(checkResultVo.getItemName());
        checkResult.setPrice(checkResultVo.getPrice());
        checkResult.setRegId(checkResultVo.getCareHistory().getRegId());
        checkResult.setPatientId(checkResultVo.getCareHistory().getPatientId());
        checkResult.setPatientName(checkResultVo.getCareHistory().getPatientName());
        checkResult.setResultStatus("0");
        checkResult.setCreateBy(checkResultVo.getCareHistory().getUserName());
        checkResult.setCreateTime(new Date());
        return checkResult;
    }
}
